﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using System.Linq;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// BootstrapAdmin 后台权限认证过滤器
    /// </summary>
    public class BootstrapAdminAuthorizeFilter : IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 异步授权方法
        /// </summary>
        /// <param name="context">过滤器上下文</param>
        /// <returns></returns>
        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // 允许匿名访问时忽略
            // 管理员组访问时忽略
            // api 请求忽略
            if (context.ActionDescriptor.EndpointMetadata.Any(meta => meta is IAllowAnonymous) ||
                context.HttpContext.User.IsInRole("Administrators") ||
                context.HttpContext.Request.Path.StartsWithSegments("/api")) return Task.CompletedTask;

            // 判断菜单授权
            var url = $"~/{context.ActionDescriptor.RouteValues["controller"]}/{context.ActionDescriptor.RouteValues["action"]}";
            if (!BootstrapAdminAuthenticationExtensions.RetrieveRolesByUrl(url).Any(context.HttpContext.User.IsInRole)) context.Result = new ForbidResult();
            return Task.CompletedTask;
        }
    }
}
